package gro.ecorrdata.edata.controller;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.io.IOException;
import java.util.UUID;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import net.coobird.thumbnailator.Thumbnails;

import gro.ecorrdata.edata.annotation.NoneAuth;
import gro.ecorrdata.edata.model.BaseResponse;
import gro.ecorrdata.edata.util.MyUtil;

/**
 * Captcha by huwhois time 2019/11/22
 */
@RestController
@RequestMapping("/file_manager")
@Configuration
public class FileManager {

    @Value("${file.datapath}")
    private String dataPath;    // 读取配置文件中的指定目录

    @Value("${file.uploadFolder}")
    private String uploadFolder;    // 读取配置文件中的指定目录

    @CrossOrigin
    @PostMapping("/uploadimg")
    public BaseResponse<Map<String, String>> uploadImage(@RequestParam(value = "upload_file") MultipartFile file, HttpServletRequest request) throws IOException {
        boolean isthumb = false;
        String thumb = request.getParameter("isthumb");
        if (thumb != null && thumb != "" && thumb.equals("1")) {
            isthumb = true;
        }
        // 根据相对路径转化为真实路径
        // String rootpath = request.getSession().getServletContext().getRealPath(File.separator);// 获得web应用的绝对路径
        // File createFile = new File(rootpath + "../data/upload/");
        String useUploadPath;   // 文件上传使用的目录
        String activePath = request.getParameter("activepath"); 
        if (activePath != null && activePath != "") {
            // 上传到指定目录
            useUploadPath = activePath + "/";
        } else {
            // 使用配置文件中的指定上传目录与当前年月新建文件夹
            LocalDateTime ldt = LocalDateTime.now();
            String today = ldt.format(DateTimeFormatter.BASIC_ISO_DATE);
            useUploadPath = uploadFolder  + "/" + today + "/";
        }

        // System.out.println(useUploadPath);
        String picDir = dataPath + useUploadPath;   // 文件绝对路径

        File createFile = new File(picDir);
        if (!createFile.exists()) {// 判断文件是否存在如果不存在则自动创建文件夹
            createFile.mkdir();
        }
        // System.out.println(picDir);
        String fileOldName = file.getOriginalFilename();
        // 上传的图片只允许是 png、jpg 或 gif 中的格式
        if (file.getOriginalFilename().contains(".png") || file.getOriginalFilename().contains(".jpg") || file.getOriginalFilename().contains(".gif")) {
            String uuidMd5 = MyUtil.md5(UUID.randomUUID().toString().replace("-", ""));// 随机生成一个唯一性的id 文件不重名
            String suffix = fileOldName.substring(fileOldName.lastIndexOf(".") + 1);
            String newFilename = uuidMd5 + "." + suffix;
            File f = new File(picDir + newFilename);
            if (f.exists()) {//上传的文件已经存在,则提示用户重新上传 apk 或者重命名
                return new BaseResponse<>(false, "上传的文件已经存在,则提示用户重新上传 apk 或者重命名", null);
            } else {
                Map<String, String> result = new HashMap<String, String>();

                file.transferTo(f); // 将上传的文件写入到系统中
                if (isthumb) {
                    String thumbFilaname = uuidMd5 + "_200." + suffix;
                    Thumbnails.of(picDir + newFilename).width(200).toFile(picDir + thumbFilaname);
                    result.put("thumb", useUploadPath + thumbFilaname);
                }
                result.put("picname", useUploadPath + newFilename);

                return new BaseResponse<>(true, "上传成功", result);
            }
        } else {
            return new BaseResponse<>(false, "上传文件失败", null);
        }
    }

    /*
     * 读取指定路径下的文件名和目录名
     */
    @NoneAuth
    @RequestMapping("/list")
    public BaseResponse<Map<String, Object>> getFileList(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        String activepath = request.getParameter("activepath");
        // System.out.println(activepath);
        String dir = "";
        if (activepath!=null && activepath!="") {
            dir = activepath;
        }

        File file = new File(dataPath + dir);
        // System.out.println(dataPath +  dir);
        File[] fileList = file.listFiles();

        ArrayList<String> dList = new ArrayList<>();
        ArrayList<Map<String, Object>> fList = new ArrayList<>();

        for (int i = 0; i < fileList.length; i++) {
            if (fileList[i].isDirectory()) {
                String fileName = fileList[i].getName();
                dList.add(fileName);
                // System.out.println("文件：" + fileName);       
                // System.out.println(fileName);     
            }
            
            if (fileList[i].isFile()) {
                File ifile = fileList[i];
                String fileName = ifile.getName();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                long size = ifile.length();
                long time = ifile.lastModified();
                // Map<String, Object> ofile = new HashMap<>();
                Map<String, Object> ofile = new HashMap<String, Object>();
                ofile.put("fileName", fileName);
                ofile.put("suffix", suffix);
                ofile.put("size", size);
                ofile.put("time", time);
                
                fList.add(ofile);
                // System.out.println("文件：" + fileName);       
                // System.out.println(fileName);       
            }
        }
        result.put("fList", fList);
        result.put("dList", dList);
        result.put("activepath", dir);
        // System.out.println(dir);
        return new BaseResponse<>(true, "", result);
    }

    /**
	 * 删除文件
	 * 
	 * @param pathname
	 * @return
	 * @throws IOException
	 */
	public static boolean deleteFile(String pathname){
		boolean result = false;
		File file = new File(pathname);
		if (file.exists()) {
			file.delete();
			result = true;
		}
		return result;
    }
    
    /**
	 * 删除文件
	 * 
	 * @param pathname
	 * @return
	 * @throws IOException
	 */
	public static boolean deleteDir(String pathname){
		boolean result = false;
		File dir = new File(pathname);
		if (dir.exists()) {
            File[] files = dir.listFiles();
            if (null == files) {
                dir.delete();
                result = true;
            }
		}
		return result;
    }

    @PostMapping("/delete")
    public BaseResponse<Map<String, Object>> deleteFile(String activePath, String fileName){
        boolean result = false;
        String dir = "";
        if (activePath!=null || activePath!="") {
            dir = activePath;
        }
        
        String pathname = dataPath + dir + "/" + fileName;
        // System.out.println(pathname);
        File file = new File(pathname);
        if (!file.exists()) {
            return new BaseResponse<>(false, "文件or文件夹不存在", null);
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File f : files) {
                    if (f.exists()) {
                        f.delete();
                    }
                }
            }
            result = file.delete();
        }
        
        if (file.isFile()) {
            result = file.delete();
        }
        
        return new BaseResponse<>(result, "OK", null);
    }
}
